<script lang="ts" setup>
import { getCurrentInstance, onMounted, onUnmounted } from 'vue'
import { onHide, onShow } from '@dcloudio/uni-app'

import { canvasHeight, canvasId, canvasWidth, canvasList, resetCanvas } from './data'

// #ifdef APP
onShow(resetCanvas)
onHide(resetCanvas)
// #endif

// #ifdef MP-TOUTIAO
const instance = getCurrentInstance()

onMounted(() => {
  if (!instance) return

  const query = uni.createSelectorQuery().in(instance.proxy)

  query
    .select('#' + canvasId)
    .node(res => canvasList.push({
      id: instance.uid,
      canvas: res.node
    }))
    .exec()
})

onUnmounted(() => {
  if (!instance) return

  const idx = canvasList.findIndex(item => item.id === instance.uid)

  ~idx && canvasList.splice(idx, 1)
})
// #endif
</script>

<template>
  <canvas
    class="off-canvas"
    :id="canvasId"
    :canvas-id="canvasId"
    type='2d'
    :style="{
      width: canvasWidth + 'px',
      height: canvasHeight + 'px',
    }"
  ></canvas>
</template>

<style lang="less" scoped>
.off-canvas {
  position: fixed;
  left: 100%;
  top: 100%;
}
</style>